package com.tonyspace.web;

import com.tonyspace.domain.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author: dell
 * @Date: 13:34 2018/5/23
 * @Description:
 */
@Api(tags={"用户接口"})
@RestController
@RequestMapping(value = "/users")
public class UserController {

    public static Map<Long,User> users = Collections.synchronizedMap(new HashMap<Long,User>());

    /**
     * get方法 /users 获取用户信息列表
     * @return
     */
    @ApiOperation(value = "获取用户列表")
    @RequestMapping(value = "/" , method = RequestMethod.GET)
    public List<User> getUserList(){
        List<User> list = new ArrayList<User>(users.values());
        return list;
    }

    /**
     * put方法, /users 创建用户数据
     * @ModelAttribute 用于绑定参数(表单数据),或者用 @RequestBody 提交的参数可以是json格式
     * @param user
     * @return
     */
    @ApiOperation(value = "创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @RequestMapping(value = "/" , method = RequestMethod.POST)
    public String postUser( @RequestBody User user){//@ModelAttribute
        users.put(user.getId(),user);
        return  "success";
    }

    /**
     * 处理 /users/{id} 来获取用户
     * url中的id值，通过 @PathVariable 绑定
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public  User getUser(@PathVariable Long id){
        return users.get(id);
    }

    /**
     * 通过put 方法更新用户
     * @param id
     * @param user
     * @return
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    public String putUser(@PathVariable Long id,@ModelAttribute User user){
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id,u);
        return "success";
    }

    /**
     * delete 方法删除用户
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id){
        users.remove(id);
        return "success";
    }


}
